// pages/order/index.js
const App = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ispay: false, // 是否支付
    pay: 0, // 0 全部 1 待支付 2 已支付 3 已完成
    order: [],
    offset: 1,
    limit: 20,
    count: 0,  // 总条数
    payData: null,
  },
  isLoading: false,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      offset: 1
    })
    this.getList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.offset < (this.data.count / this.data.limit)) {
      this.setData({
        offset: this.data.offset + 1
      })
      this.getList();
    }
  },

  // 请求
  getList(status) {
    console.log('stat:',status)
    if (this.isLoading) return;
    this.isLoading = true;
    let url = 'mp/order/list';
    let param = {
      limit: this.data.limit,
      offset: this.data.offset,
      type: 2
    };
    if (status && status > 0) param.status = status;
    App.ajax(url, 'GET', param).then(res => {
      this.isLoading = true;
      console.log(res);
      if (res.status === 10000) {
        if (offset !== 1) {
          this.setData({
            order: this.order.concat(res.data.rows),
            count: res.data.count
          });  
        } else {
          this.setData({
            order: res.data.rows,
            count: res.data.count
          });
        }
      } else {
        App.prompts(res.msg);
      }
    }).catch(err => {
      this.isLoading = true;
      console.log(err)
    })
  },

  // 自定义方法
  goPay (e) {
    console.log(e);
    let item = e.detail;
    this.setData({
      ispay: this.data.ispay ? false : true,
      payData: this.data.ispay ? null : item
    })
  },
  upPay (e) {
    let id = e.currentTarget.dataset.id;
    this.setData({
      pay: id
    });
    this.getList(id);
  },
  del(e) {
    console.log(e);
    let index = e.detail;
    let order = JSON.parse(JSON.stringify(this.data.order));
    console.log('order', order[index])
    let url = 'mp/order/' + order[index].id;
    App.ajax(url, 'DELETE', '').then(res => {
      if (res.status === 10000) {
        order.splice(index, 1);
        if (order.length < 3) {
          this.getList();
        } else {
          this.setData({
            order: order
          })
        }
      }
      setTimeout(function(){
        App.prompts(res.msg)
      }, 100)
    }).catch(err => {
      console.log(err)
    })
  },
  upgetlist() {
    this.setData({
      offset: 1,
      limit: 20,
      order: [],
      ispay: false
    })
    this.getList();
  }
})